<template>
  <view class="content">
    <uni-search-bar placeholder="请输入关键词搜索" radius="100" cancel-button="none" v-model="kw" class="uni-search" @confirm="confirm" @clear="clear" />
    <view v-if="blogs.length==0" class="none">
      <image src="/static/icons(1)/nodata.png" mode="widthFix" class="logo"></image>
      <text>{{textData}}</text>	
    </view>
    <view v-else v-for="(item,index) in blogs" class="item-container" @click="toBlogDetail(item.id)">
      <text class="item-title">{{item.title}}</text>
      <rich-text :nodes="item.description" class="item-desc"></rich-text>
      <image :src="item.picture" mode="widthFix" class="item-focus"></image>
      <image :src="item.user.avatar" mode="aspectFill" class="item-avatar" @click.stop="showBlogger(item.user)"></image>
      <view>
        <text v-for="(tag, idx) in item.tags" :key="tag" class="item-tag">{{tag}}</text>
      </view>
      <view class="icon-container">
        <span
          :class="goodIds.includes(item.id) ? 'iconfont icon-dianzan ic-red' : 'iconfont icon-dianzan ic-gray'"
          @click.stop="changeGood(item.id)"
          style="display: inline-block; margin-right: 5px;"
        ></span>
        <text class="icon-text">{{item.good}}</text>
        <image src="/static/icons(1)/ic_comment.png" class="icon"></image>
        <text class="icon-text">{{item.comments.length}}</text>
        <image src="/static/icons(1)/ic_count.png" class="icon"></image>
        <text class="icon-text">{{item.readCount}}</text>
      </view>
      <text class="iconfont icon-jiantouxia icon-tag" @click.stop="drop(item.id)"></text>
    </view>
    <view class="bottom" v-if="blogs.length==count">
      ---已到达底部---
    </view>
    <dialog-shell title="博主实况" ref="shell">
      <text style="padding: 20rpx;">{{blogger}}</text>
    </dialog-shell>
  </view>
</template>

<script>
import { fail } from 'assert';
import { compile } from "vue";
import params from '../../utils/params';

export default {
  data() {
    return {
      textData: "没有数据,请刷新！",
      blogs: [],
      page: 0,
      size:3,
      count: -1,
      searching:false,
      kw: '',
      goodIds: [],
      blogger:''
    }
  },
  onLoad() {
    this.$noti.add(this.$params.noti_refresh_count,this.notiCount,this)
    this.$noti.add(this.$params.noti_change_good,this.notiGood,this)
    //加载数据
    let ids = uni.getStorageSync(this.$params.key_good_ids);
    if (ids) {
      this.goodIds = ids;
      console.log('从缓存加载的goodIds:', this.goodIds);
    }
    const blogs = uni.getStorageSync(this.$params.key_blogs);
    if (blogs) {
      this.blogs = blogs
      this.count = blogs.length
      console.log('从缓存加载的博客:', blogs[0]);
    } else {
      this.getPagedBlogs();
    }
  },
  onUnload(){
    this.$noti.remove(this.$params.noti_refresh_count,this) 
    this.$noti.remove(this.$params.noti_change_good,this)
  },
  onPullDownRefresh(){
    this.searching=false
    this.kw=''
    this.page=0
    this.count=-1
    this.blogs=[]
    this.getPagedBlogs()
  },
  onReachBottom() {
    if(this.searching || this.blogs.length == this.count){
      return
    }
    this.page++
    this.getPagedBlogs()
  },
  methods: {
    refreshComments(cmt){
      this.blogs.forEach(b=>{
        if(b.id==cmt.blogId){
          b.comments=[...b.comments,cmt]
        }
      })
    },
    showBlogger(user){
      this.blogger="作者："+user.nickName+"\n联系方式："+user.email
      this.$refs.shell.showDialog()
    },
    notiGood(info){
      let id = info.id
      let count = info.count
      let ids = uni.getStorageSync(this.$params.key_good_ids)
      if(ids){
        this.goodIds=ids
      }
      this.blogs.forEach(b=>{
        if(b.id==id){
          b.good=count
        }
      })
    },
    notiCount(info){
      console.log("接收到通知refresh count");
      let id =info.id
      let count = info.count
      this.refreshReadCount(id,count)
    },
    refreshReadCount(id,count){
      this.blogs.forEach(b=>{
        if(b.id==id){
          b.readCount=count
        }
      })
    },
    toBlogDetail(id) {
      uni.navigateTo({
        url: '/pages/blog/blog?id='+id 
      });
    },
    drop(id){
      uni.showActionSheet({
        itemList: ["收藏","删除","举报"],
        success: res => {
          switch(res.tapIndex){
            case 0:
              uni.showToast({
                title:'功能善待完善!'
              });
              break;
            case 1:
              uni.showModal({
                title: '警告',
                content: '确认要删除吗',
                showCancel: true,
                cancelText: '算了',
                confirmText: '删除',
                success: res => {
                  if(res.confirm){
                    uni.showToast({
                      title: '没有删除权限，请登录！',
                      icon:'none'
                    });
                  }
                },
                fail: () => {},
                complete: () => {}
              });
          }
        },
        fail: () => {},
        complete: () => {}
      });
    },
    changeGood(id){
      console.log('点击点赞:', id);
      console.log('当前goodIds:', this.goodIds);
      
      // 检查当前博客是否已点赞
      const isLiked = this.goodIds.includes(id);
      
      if (isLiked) {
        // 取消点赞
        this.goodIds = this.goodIds.filter(blogId => blogId !== id);
        console.log('取消点赞后的goodIds:', this.goodIds);
      } else {
        // 点赞
        this.goodIds = [...this.goodIds, id];
        console.log('点赞后的goodIds:', this.goodIds);
      }
      
      // 更新本地存储
      uni.setStorageSync(this.$params.key_good_ids, this.goodIds);
      
      // 发送请求到服务器
      this.postGood(id, !isLiked);
    },
    postGood(id,good){
      uni.showLoading({
        title:"点赞......",
        mask:false
      });
      let url = this.$params.host
      let action = good ? this.$params.action_good : this.$params.action_del_good
      url +=action
      let data={
        "id":id
      }
      this.$req.postQuery(url,data,res=>{
        console.log('点赞请求响应:', res);
        this.blogs.forEach(blog=>{
          if(blog.id==id){
            blog.good = res.data.data
          }
        })
      }, ()=>{
        uni.hideLoading()
      })
    },
    confirm(e) {
      let kw = e.value
      if(kw.length>0){
        this.searching=true
        this.blogs=[]
        this.page=0
        this.count=-1
        uni.showLoading({
          title:'搜索中......',
          mask:false
        });
        this.$req.get(this.$params.host+this.$params.action_search+kw, res=>{
          res.data.data.forEach(blog=>{
            blog.picture=this.$params.host+blog.picture
            blog.user.avatar=this.$params.host+blog.user.avatar
          })
          this.blogs=[...this.blogs,...res.data.data]
        }, ()=>{
          uni.hideLoading()
        })
      }
    },
    clear(){
      
    },
    getPagedBlogs(){
      let header ={
        "content-type" : "application/json;charset=UTF-8",
        "page":this.page,
        "size":this.size,
      }
      this.$req.getWithParams(this.$params.host+this.$params.action_blogs_page, header ,res =>{
        res.data.data.forEach(blog=>{
          blog.picture = this.$params.host + blog.picture
          blog.user.avatar = this.$params.host + blog.user.avatar
        })
        this.blogs= [...this.blogs,...res.data.data]
        this.count = res.data.message
        //将获取的最新数据保存到缓存
        uni.setStorageSync(this.$params.key_blogs,this.blogs)
      },()=>{
        uni.stopPullDownRefresh()
      })
    },
    getTopBlogs(){
      this.$req.get(params.hst+this.$params.action_top_blogs, res =>{
        res.data.data.forEach(blog=> {
          blog.picture = this.$params.host + blog.picture
          blog.user.avatar = this.$params.host + blog.user.avatar
        })
        this.blogs = res.data.data
      })
    },
    goToBlog(id) {
      uni.navigateTo({
        url: `/pages/blog/blog?id=${id}`
      });
    },
    fetchBlogList() {
      uni.request({
        url: 'https://你的接口地址/api/blogList',
        method: 'GET',
        success: res => {
          this.blogList = res.data;
        },
        fail: () => {
          console.error('获取博客列表失败');
        }
      });
    },
  }
}
</script>

<style>
  @import url("index.css");
  
  /* 可以在这里添加调试样式 */
  .ic-red {
    color: red !important;
  }
  
  .ic-gray {
    color: gray !important;
  }
</style>